package com.dsideal.cloud.cas.client.filter;

import com.dsideal.cloud.auth.common.util.jwt.IJWTInfo;
import com.dsideal.cloud.auth.core.config.UserAuthenticationConfig;
import com.dsideal.cloud.cas.client.config.MutableHttpServletRequest;
import com.dsideal.cloud.cas.client.cache.RedisUserCache;
import com.dsideal.cloud.cas.client.cas.entity.CasUserDetails;
import com.dsideal.cloud.cas.client.properties.RequestProperties;
import com.dsideal.cloud.cas.client.utils.JwtTokenUtil;
import com.dsideal.cloud.common.log.DsLogger;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 用户Token过滤器
 *
 * @author suny
 * @date 2018/11/23
 */
public class UserTokenFilter extends UsernamePasswordAuthenticationFilter implements Serializable {

    private final static DsLogger log = DsLogger.buildLogger(UserTokenFilter.class);


    @Autowired
    private UserAuthenticationConfig userAuthenticationConfig;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisUserCache redisUserCache;

    @Autowired
    private RequestProperties requestProperties;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpServletRequest request1 = (HttpServletRequest) servletRequest;
        MutableHttpServletRequest request=new MutableHttpServletRequest(request1);
        try {
            if (shouldFilter(request)) {
                String token = parseToken(request);
                CasUserDetails casUserDetails = null;

                //  解析token 获得用户信息
                casUserDetails = getUserFromToken(token);

                // 利用username从redis获取token 判断token是否相同
                String cacheKey = request.getHeader(requestProperties.getUserAgent())  + casUserDetails.getName();
                String cacheToken = redisUserCache.getTokenFromCache(cacheKey);
                if (StringUtils.isBlank(cacheToken) || !cacheToken.equals(token)) {

                    request.getRequestDispatcher("/login").forward(request, response);
                    return;
                }

            }
//            如果数据库查到了token就是过期token，拿到名字重新生成，放header
//                    需要在生成token插入数据库
        }catch (ExpiredJwtException ejt){
            //过期token放行，使其走刷新token接口
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("UserTokenFilter error {}", e);
        }

        chain.doFilter(request, response);
    }

    private boolean shouldFilter(HttpServletRequest request) {
        return StringUtils.isNotBlank(request.getHeader(userAuthenticationConfig.getTokenHeader()));
    }



    /**
     * 从请求头中获取token
     *
     * @param request
     * @return
     */
    private String parseToken(HttpServletRequest request) {
        return request.getHeader(userAuthenticationConfig.getTokenHeader());
    }

    /**
     * 解析token中的用户信息
     *
     * @param token
     * @return
     */
   private CasUserDetails getUserFromToken(String token) throws Exception {
        IJWTInfo jwtInfo = jwtTokenUtil.getInfoFromToken(token);
        return CasUserDetails.fromJWTInfo(jwtInfo);
    }

}
